#include <brpc/channel.h>
#include <thread>
#include "main.pb.h"
#include "../../common/channel.hpp"

int main() {
    
    auto service_mgr = std::make_shared<bite_im::ServiceManager>();
    service_mgr->declared("/service");

    service_mgr->onServiceOnline("127.0.0.1:8080", "/service");
    while (1)
    {

        // 3. 通过Rpc信道管理对象，获取提供Echo服务的信道
        auto channel = service_mgr->choose("/service");
        if (!channel)
        {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
        }
        // 4. 发起EchoRpc调用
        example::EchoService_Stub stub(channel.get());
        // 构造请求消息
        example::EchoRequest req;
        req.set_message("hello~world~！");
        // 异步调用Echo方法
        brpc::Controller *cntl = new brpc::Controller();          // 控制调用过程（如超时,错误）
        example::EchoResponse *rsp = new example::EchoResponse(); // 接收响应

        stub.Echo(cntl, &req, rsp, nullptr); // 同步调用
        if (cntl->Failed())
        {
            std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
            delete cntl;
            delete rsp;
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
        }
        std::cout << "收到响应: " << rsp->message() << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        service_mgr->onServiceOffline("127.0.0.1:8080", "/service");
    }

    return 0;
}